<template>
	<div class="notice-detail-page">
		<!-- 导航栏 -->
		<van-nav-bar :title="noticeData.noticeTitle || '通知详情'" left-text="返回" left-arrow fixed placeholder @click-left="onBack" />

		<!-- 加载状态 -->
		<div v-if="loading" class="loading-container">
			<van-loading type="spinner" color="#1989fa" vertical> 加载中... </van-loading>
		</div>

		<!-- 通知详情内容 -->
		<div v-else-if="noticeData.noticeId" class="detail-content">
			<!-- 标题 -->
			<div class="notice-title">{{ noticeData.noticeTitle }}</div>

			<!-- 元信息 -->
			<div class="notice-meta">
				<span class="meta-item">
					<van-icon name="clock-o" />
					{{ noticeData.createTime }}
				</span>
				<span class="meta-item">
					<van-icon name="manager-o" />
					{{ noticeData.createBy || '系统管理员' }}
				</span>
			</div>

			<!-- 分割线 -->
			<van-divider />

			<!-- 内容 -->
			<div class="notice-content" v-html="noticeData.noticeContent"></div>

			<!-- 已读信息展示 -->
			<div class="read-info" v-if="!loading">
				<van-icon name="eye-o" color="#969799" />
				<span class="read-count-text">{{ readCount }} 人已阅读</span>
			</div>

			<!-- 附件列表 -->
			<div v-if="noticeData.attachments && noticeData.attachments.length > 0" class="attachments">
				<div class="attachment-title">
					<van-icon name="paperclip" />
					附件
				</div>
				<div v-for="(file, index) in noticeData.attachments" :key="index" class="attachment-item" @click="downloadFile(file)">
					<van-icon name="description" />
					<span>{{ file.fileName }}</span>
					<van-icon name="arrow-down" />
				</div>
			</div>
		</div>

		<!-- 加载失败 -->
		<van-empty v-else description="通知不存在或已删除" />
	</div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getNoticeDetail, markNoticeAsRead, getFileList } from '@/api/notice'

export default {
	name: 'NoticeDetailPage',
	setup() {
		const route = useRoute()
		const router = useRouter()

		const loading = ref(true)
		const noticeData = ref({})
		const isReaded = ref(false)
		const readCount = ref(0)

		// 返回上一页
		const onBack = () => {
			router.back()
		}

		// 下载文件
		const downloadFile = (file) => {
			if (!file.fileUrl) {
				showToast('文件链接不存在')
				return
			}

			console.log('下载文件:', file)

			// 创建一个隐藏的a标签并触发点击
			const link = document.createElement('a')
			link.href = file.fileUrl
			link.download = file.fileName || '附件'
			link.target = '_blank'
			link.style.display = 'none'
			document.body.appendChild(link)
			link.click()

			// 清理
			setTimeout(() => {
			document.body.removeChild(link)
			}, 200)
		}

		// 检查是否已读
		const checkIsReaded = async (noticeId) => {
			try {
				const { isReaded: isReadedApi } = await import('@/api/notice')
				const response = await isReadedApi({ id: noticeId })
				if (response.code === '0') {
					isReaded.value = response.data === true || response.data === '1'
				}
			} catch (error) {
				console.error('检查已读状态失败:', error)
			}
		}

		// 获取已读数量
		const getReadCount = async (noticeId) => {
			try {
				const { selectReadCountByNoticeId } = await import('@/api/notice')
				const response = await selectReadCountByNoticeId({ id: noticeId })
				if (response.code === '0') {
					readCount.value = response.data || 0
				}
			} catch (error) {
				console.error('获取已读数量失败:', error)
			}
		}

		// 标记为已读（自动调用，不显示提示）
		const markAsRead = async (noticeId) => {
			if (isReaded.value) {
				return
			}

			try {
				await markNoticeAsRead(noticeId)
				isReaded.value = true
				readCount.value += 1
				console.log('自动标记已读成功')
			} catch (error) {
				console.error('标记已读失败:', error)
			}
		}

		// 获取附件列表
		const queryFiles = async (noticeId) => {
			if (!noticeId) {
				return
			}

			try {
				const response = await getFileList(noticeId)
				if (response.code === '0' && response.data) {
					// 将附件数据格式化为页面需要的格式
					const attachments = response.data.map((file) => ({
						id: file.id,
						fileName: file.originalFileName || file.name || '未知文件',
						fileUrl: file.url,
						fileExtension: file.fileExtension,
						fileSize: file.fileSize,
					}))

					// 更新通知数据中的附件列表
					noticeData.value.attachments = attachments
					console.log('获取附件列表成功:', attachments)
				}
			} catch (error) {
				console.error('获取附件列表失败:', error)
			}
		}

		// 加载通知详情
		const loadDetail = async () => {
			const noticeId = route.query.id || route.params.id

			if (!noticeId) {
				showToast('缺少通知ID')
				loading.value = false
				return
			}

			try {
				loading.value = true

				const response = await getNoticeDetail(noticeId)

				if (response.code === '0' && response.data) {
					noticeData.value = response.data

					// 检查已读状态
					await checkIsReaded(noticeId)
					// 获取已读数量
					await getReadCount(noticeId)
					// 获取附件列表
					await queryFiles(noticeId)

					// 自动标记为已读（如果还未读）
					if (!isReaded.value) {
						await markAsRead(noticeId)
					}
				} else {
					showToast(response.msg || '获取详情失败')
				}
			} catch (error) {
				console.error('获取通知详情失败:', error)
				showToast('网络错误，请稍后重试')
			} finally {
				loading.value = false
			}
		}

		onMounted(() => {
			loadDetail()
		})

		return {
			loading,
			noticeData,
			readCount,
			onBack,
			downloadFile,
		}
	},
}
</script>

<style lang="less" scoped>
.notice-detail-page {
	min-height: 100vh;
	background-color: #f7f8fa;
}

.loading-container {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 1000;
}

.detail-content {
	background: #fff;
	padding: 16px;
	min-height: calc(100vh - 46px);

	.notice-title {
		font-size: 18px;
		font-weight: 600;
		color: #323233;
		line-height: 28px;
		margin-bottom: 12px;
	}

	.notice-meta {
		display: flex;
		align-items: center;
		gap: 16px;
		margin-bottom: 16px;

		.meta-item {
			font-size: 12px;
			color: #969799;
			display: flex;
			align-items: center;
			gap: 4px;
		}
	}

	.notice-content {
		font-size: 15px;
		line-height: 24px;
		color: #323233;
		word-wrap: break-word;
		word-break: break-all;

		// 处理富文本样式
		:deep(img) {
			max-width: 100%;
			height: auto;
			display: block;
			margin: 12px 0;
		}

		:deep(p) {
			margin: 8px 0;
		}

		:deep(a) {
			color: #1989fa;
			text-decoration: underline;
		}
	}

	.attachments {
		margin-top: 24px;
		padding-top: 16px;
		border-top: 1px solid #ebedf0;

		.attachment-title {
			font-size: 14px;
			font-weight: 500;
			color: #323233;
			margin-bottom: 12px;
			display: flex;
			align-items: center;
			gap: 6px;
		}

		.attachment-item {
			display: flex;
			align-items: center;
			gap: 8px;
			padding: 12px;
			background: #f7f8fa;
			border-radius: 8px;
			margin-bottom: 8px;
			cursor: pointer;
			transition: all 0.3s;

			&:active {
				transform: scale(0.98);
				background: #ebedf0;
			}

			span {
				flex: 1;
				font-size: 14px;
				color: #323233;
			}
		}
	}

	.read-info {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16px;
		margin: 16px 0;
		background: #f7f8fa;
		border-radius: 8px;
		gap: 6px;

		.read-count-text {
			font-size: 14px;
			color: #969799;
		}
	}
}

:deep(.van-nav-bar) {
	background: #fff;
}
</style>
